package pl.task;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class TaskEntityActivity extends Activity
{
    private static final String TAG = "TaskEntityActivity";
    private static final int RESULT_ADD = 1;
    private static final int RESULT_EDIT = 2;

    private Cursor cursor;
    private SimpleCursorAdapter simpleCursorAdapter;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        boolean result = false;

        Log.d(TAG, "onKeyDown " + keyCode);
        if (keyCode == KeyEvent.KEYCODE_BACK)
        {
            result = true;
            finish();
        }

        return result;
    }

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        Log.d(TAG, "onCreate");

        super.onCreate(savedInstanceState);
        setContentView(R.layout.task);

        final Button addButton = (Button) findViewById(R.id.addTaskButton);
        addButton.setOnClickListener(new OnClickListener()
            {
                @Override
                public void onClick(View v)
                {
                    final Intent targetIntent = new Intent(Intent.ACTION_INSERT, Task.CONTENT_URI);
                    startActivityForResult(targetIntent, RESULT_ADD);
                }
            });

        populateList();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        switch (requestCode)
        {
            case RESULT_ADD:
            case RESULT_EDIT:
                if (resultCode == Activity.RESULT_OK)
                {
                    Log.d(TAG, "TODO: save: " + data.getLongExtra("_ID", -1));
                    final ContentValues values = new ContentValues();
                    if (requestCode == RESULT_EDIT)
                    {
                        values.put(Task._ID, data.getLongExtra("_ID", -1));
                    }
                    values.put(Task.NAZWA, data.getStringExtra("nazwa"));
                    values.put(Task.OPIS, data.getStringExtra("opis"));
                    if (requestCode == RESULT_EDIT)
                    {
                        getContentResolver().update(
                            Uri.parse(Task.CONTENT_URI + "/" + data.getLongExtra("_ID", -1)),
                            values,
                            null,
                            null);
                    }
                    else
                    {
                        getContentResolver().insert(
                            Task.CONTENT_URI,
                            values);
                    }
                }
                else
                {
                    Log.d(TAG, "TODO: discard");
                }
                break;
            default:
                super.onActivityResult(requestCode, resultCode, data);
        }
    }

    private void populateList()
    {
        cursor = getCursor();
        final String[] fields = new String[]
            {
                Task.NAZWA,
            };
        simpleCursorAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_multiple_choice, cursor, fields, new int[]
            {
                android.R.id.text1,
                android.R.id.selectedIcon,
            });
        final ListView listView = (ListView) findViewById(R.id.listTask);
        listView.setAdapter(simpleCursorAdapter);
        listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        listView.setOnItemClickListener(new OnItemClickListener()
            {
                public void onItemClick(AdapterView<?> parent, View view, int position, long id)
                {
                    // When clicked, show a toast with the TextView text
                    Toast.makeText(getApplicationContext(), "Editing " + ((TextView) view).getText(), Toast.LENGTH_SHORT).show();
                    edit(id);
                }
            });
        registerForContextMenu(listView);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo)
    {
        menu.setHeaderTitle("Task");
        AdapterView.AdapterContextMenuInfo info;
        try
        {
            info = (AdapterView.AdapterContextMenuInfo) menuInfo;
        }
        catch (ClassCastException e)
        {
            Log.e(TAG, "bad menuInfo", e);
            return;
        }
        final long id = simpleCursorAdapter.getItemId(info.position);
        {
            final MenuItem menuItem = menu.add(0, 0, 0, "Edytuj: " + cursor.getString(1));
            menuItem.setOnMenuItemClickListener(new OnMenuItemClickListener()
                {
                    @Override
                    public boolean onMenuItemClick(MenuItem item)
                    {
                        edit(id);
                        return true;
                    }
                });
        }
        {
            final MenuItem menuItem = menu.add(0, 0, 0, "Skasuj: " + cursor.getString(1));
            menuItem.setOnMenuItemClickListener(new OnMenuItemClickListener()
                {
                    @Override
                    public boolean onMenuItemClick(MenuItem item)
                    {
                        getContentResolver().delete(Uri.parse(Task.CONTENT_URI + "/" + id), null, null);
                        return true;
                    }
                });
        }
    }

    private Cursor getCursor()
    {
        final Uri uri = Task.CONTENT_URI;
        String[] projection = new String[]
            {
                Task._ID,
                Task.NAZWA,
            };
        String selection = "";
        String[] selectionArgs = null;
        String sortOrder = null; //DummyContentProvider.NAZWA + " COLLATE LOCALIZED ASC";

        return managedQuery(uri, projection, selection, selectionArgs, sortOrder);
    }

    private Cursor getEditCursor(long id)
    {
        final Uri uri = Task.CONTENT_URI;
        String[] projection = new String[]
            {
                Task._ID,
                Task.NAZWA,
                Task.OPIS,
            };
        String selection = "Task._id = " + id;
        String[] selectionArgs = null;
        String sortOrder = null; //DummyContentProvider.NAZWA + " COLLATE LOCALIZED ASC";

        return managedQuery(uri, projection, selection, selectionArgs, sortOrder);
    }

    private void edit(long id)
    {
        final Intent targetIntent = new Intent();
        targetIntent.setClass(TaskEntityActivity.this, TaskEntityEditActivity.class);
        targetIntent.putExtra("_ID", id);
        final Cursor editCursor = getEditCursor(id);
        editCursor.moveToFirst();
        targetIntent.putExtra("nazwa", editCursor.getString(1));
        targetIntent.putExtra("opis", editCursor.getString(2));
        editCursor.close();
        startActivityForResult(targetIntent, RESULT_EDIT);
    }
}
